package com.weixin.reflection.reflectionTest;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName ReflectionTest
 * @Description 用于做测试
 * @date 2022/2/21 10:33
 * @author: wx
 * @Version 1.0
 */
public class ReflectionTest {

    //反射获取该类与父类中公开的属性
    @Test
    public void getTest() {
        Class<Human> classz = Human.class;
        Field[] fields = classz.getFields();
        for (Field f : fields) {
            System.out.println(f);
        }
    }

    //获取运行时类的所有属性（不包括父类的属性）
    @Test
    public void getDeclared() throws Exception {
        Class<Human> classz = Human.class;
        Field[] declaredFields = classz.getDeclaredFields();
        Constructor<Human> constructor = classz.getConstructor();
        Human human = constructor.newInstance();
        human.setAge(20);
        for (Field f : declaredFields) {
            System.out.println("this is humen's field" + f);
            String name = f.getName();
            System.out.println(name);
        }
    }

    //获取自己的父类
    @Test
    public void getSuperClass() throws NoSuchFieldException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<Human> classz = Human.class;
        Class superclass = classz.getSuperclass();
        Human human = classz.newInstance();
        Field name = classz.getDeclaredField("name");
        name.setAccessible(true);
        name.set(human,"tome");
        System.out.println(superclass);
        System.out.println(name.get(human));

        System.out.println("----------------------->");
        Method show = classz.getDeclaredMethod("show", null);
        //保证挡墙方法可访问
        show.setAccessible(true);
        String returnValue = (String) show.invoke(human);
        System.out.println(returnValue);
    }

}
